#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 读写文本数据
问题: 你需要读写各种不同编码的文本数据，比如ASCII，UTF-8或UTF-16编码等。
提示 : 
"""
import os
import sys

def recipe1():
    '''读取文本文件'''
    # 使用read方法
    with open('../somefile.txt', 'rt') as f:
        data = f.read()
    print(f"{data = }")

    # 使用迭代器
    with open('../somefile.txt', 'rt') as f:
        for line in f:
            print(f"{line = }")

def recipe2():
    '''写入一个文本文件:写入一个文本文件''' 
    filename = '01_rw_text.txt' 
    with open(filename, 'wt') as f:
        # Write chunks of text data
        f.write('text1')
        # Redirected print statement
        print('text2', file=f)

    printfile(filename)
    os.remove(filename)

def recipe3():
    print(f"{sys.getdefaultencoding() = }")
    with open('../chinese.txt', 'rt', encoding='utf-8') as f: # 必须指定utf-8
        print(f"{f.read() = }")


def printfile(filename):
    with open(filename, 'rt') as f:
        print(f"{f.read() = }")
    
def main():
    print('recipe1'.center(20, '*'))
    recipe1() 
    print('recipe2'.center(20, '*'))
    recipe2() 
    print('recipe3'.center(20, '*'))
    recipe3() 

if __name__ == '__main__':
    main()         